#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# Author: DisNight
# Create: 2020-12-28
# ******************************************************************************/
"""
Method of file manipulation
"""
import os
import json
import logging

logging.getLogger().setLevel(logging.INFO)


def load_simple_file(file_path, skip_lines=0):
    """
    load simple file
    Args:
        file_path: file_path
        skip_lines: skip_lines

    Returns:
        result: result
    """
    if not os.path.exists(file_path):
        return []
    result = []
    with open(file_path, "r", encoding="utf-8-sig") as f:
        try:
            for i in range(skip_lines):
                next(f)
        except Exception as e:
            return []
        for line in f:
            result.append(line.strip())
    return result


def save_simple_file(dir_path, file_name, data):
    """
    save simple file
    Args:
        dir_path: dir path
        file_name: file name
        data: data

    Returns:
        True or False
    """
    if os.path.isfile(dir_path):
        return False
    _ = not os.path.exists(dir_path) and os.makedirs(dir_path)
    if os.path.isdir(os.path.join(dir_path, file_name)):
        return False
    with open(os.path.join(dir_path, file_name), "a+") as f:
        for element in data:
            if isinstance(element, list):
                f.write(",".join(element) + os.linesep)
            else:
                f.write(element + os.linesep)
    return True


def save_dict_file(dir_path, file_name, data):
    """

    Args:
        dir_path:
        file_name:
        data:

    Returns:

    """
    if not isinstance(data, dict):
        logging.error("illegal data type: %s", str(type(data)))
        return False
    if os.path.isfile(dir_path) or os.path.isdir(os.path.join(dir_path, file_name)):
        logging.error("illegal save file path dir[%s] file[%s]", dir_path, file_name)
        return False
    _ = not os.path.exists(dir_path) and os.makedirs(dir_path)
    with open(os.path.join(dir_path, file_name), "a") as f:
        try:
            json.dump(data, f)
        except Exception as e:
            logging.error("json dump failed: %s", str(e))
            return False
    return True


def load_dict_file(filename):
    if not os.path.isfile(filename):
        logging.error("path: %s not exist", filename)
        return None
    result = None
    with open(filename, "r") as f:
        try:
            result = json.load(f)
        except json.JSONDecodeError as jde:
            logging.error("json decode error: %s", str(jde))
            return None
        except TypeError as te:
            logging.error("json load typeerror: %s", str(te))
            return None
    return result
